
var React = require("react");
var Dialog = require("../dialog/dialog.jsx");
var Util = require("../util/util.js");
require("./upload.scss");
var Upload = React.createClass({
    getInitialState:function(){
        return{
            uploadDialog:true,
            options:this.props.options || {}
        }
    },
    componentWillReceiveProps: function(nextProps) {
        this.setState({
            options:nextProps.options
        });
    },
    /**
     * 图片上传方法
     * */
    submitUpdate:function(){
        var {options} = this.state;
        var {uploadFailedCbk} = this.props;
        var updateForm = this.refs.upload_form;
        //获取当前文件的文件名称
        var filePath = $(updateForm).find("input[type=file]").val();
        var fileName = filePath.match(/[^\\]+\.[^\(]+/i)[0];
        var _this = this;
        $(updateForm).ajaxSubmit({
            type: "post",
            url: options.url,
            success: function (data) {
                //if($.browser.msie && parseFloat($.browser.version) < 10.0){
                //    data = $(data).text();
                //}
                data = JSON.parse(data);
                if(data.success){//如果上传成功
                    data.fileName = fileName;
                    _this.props.uploadCallback(data,options);
                }else{//上传失败
                    if(uploadFailedCbk){
                        uploadFailedCbk(data);
                    }else{
                        Util.alertMessage(data.error);
                    }
                      _this.props.closeUpload();
                }
                //重置表单
                updateForm.reset();
                _this.props.onClose();
                return false;
            }
        });

    },
    render:function(){
        return(<div>
            <Dialog onClose={this.props.onClose} width="600" title="选择图片">
                <div className="upload-dialog">
                    <form ref='upload_form' encType="multipart/form-data">
                        <input className="repeat-file" type="file" onChange={this.submitUpdate} ref='update_input' name="updatefile" />
                        <button type="button" className="button paging">上传图片</button>
                    </form>
                    <p className="upload-desc">{this.props.desc}</p>
                </div>
            </Dialog>
        </div>);
    }
});

module.exports = Upload;